<?php
/**
 * Global configuration
 *
 * PHP version 5
 *
 * @category   Web
 * @package    Data2People
 * @subpackage Files
 * @author     Mike Bevz <mike.bevz@data2people.com>
 * @copyright  2007-2008 (c) Mike Bevz
 * @license    The BSD License http://data2people.com/license.txt
 * @version    SVN: $Id: global.php 13 2008-12-01 16:16:50Z michael.bevz $
  */

/**
 * Performs initialization
 *
 * @return void
 *
 */
function initConfig() {
    initZF();
    initConfigXML();
    initTestEnv();
    //initCache();
    initSmarty();
    initDoctrine();
    initLocale();
    //initSession();
    initLogger();
    //initAuth();
}


/**
 * Setups includes & Zend Framework
 *
 * @return void
 *
 */
function initZF()
{
    set_include_path(  dirname(__FILE__) . DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'libs'
    . PATH_SEPARATOR . dirname(__FILE__) . DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.
    'libs'.DIRECTORY_SEPARATOR.'doctrine'.DIRECTORY_SEPARATOR.'lib'
    . PATH_SEPARATOR . dirname(__FILE__) . DIRECTORY_SEPARATOR.'..'.
    DIRECTORY_SEPARATOR.'libs'.DIRECTORY_SEPARATOR.'doctrine'.DIRECTORY_SEPARATOR
    . PATH_SEPARATOR . dirname(__FILE__) . DIRECTORY_SEPARATOR.'..'
/*    DIRECTORY_SEPARATOR.'libs'.DIRECTORY_SEPARATOR.'doctrine'.DIRECTORY_SEPARATOR.
    'tests'.DIRECTORY_SEPARATOR.'DoctrineTest'*/
    . PATH_SEPARATOR . dirname(__FILE__) . DIRECTORY_SEPARATOR.'..'.
    DIRECTORY_SEPARATOR.'libs'.DIRECTORY_SEPARATOR.'doctrine'.DIRECTORY_SEPARATOR.
    'tests'
    . PATH_SEPARATOR . dirname(__FILE__) . DIRECTORY_SEPARATOR.'..'
    . PATH_SEPARATOR . dirname(__FILE__) . DIRECTORY_SEPARATOR.'Model'
    . PATH_SEPARATOR . dirname(__FILE__) . DIRECTORY_SEPARATOR.'Model'
                            .DIRECTORY_SEPARATOR.'BaseClasses'
    . PATH_SEPARATOR . dirname(__FILE__) . DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'libs'
                                         .DIRECTORY_SEPARATOR.'smarty'
    . PATH_SEPARATOR . dirname(__FILE__) . DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR
    /*. PATH_SEPARATOR . dirname(__FILE__) . DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR
                     .'libs'.DIRECTORY_SEPARATOR.'jsPacker'
    . PATH_SEPARATOR . dirname(__FILE__) . DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR
                     .'libs'.DIRECTORY_SEPARATOR.'FirePHPLibrary'.DIRECTORY_SEPARATOR.'lib'*/
    . PATH_SEPARATOR . '/usr/local/lib/php'
    . PATH_SEPARATOR . get_include_path());

    require_once 'Zend/Loader.php';
    Zend_Loader::registerAutoload('Zend_Loader');

    /* Init registry */
    require_once 'Zend/Registry.php';

    Zend_Registry::set('ROOT_DIRECTORY', realpath(dirname(__FILE__)
    .DIRECTORY_SEPARATOR.'..'));
    Zend_Registry::set('APP_DIRECTORY', realpath(dirname(__FILE__)
    .DIRECTORY_SEPARATOR));
    
    defined('APP_PATH')
            or define('APP_PATH', dirname(__FILE__));
    
    /**
     * For debugging purposes
     * ps. Do not use for command line
     */

    /*if (array_key_exists('HTTP_HOST', $_SERVER)) {
        define('USE_FB', true);
        include 'FirePHPCore/fb.php';
    }*/

}




/**
 * Inits Smarty templace engine
 *
 */
function initSmarty()
{
    $config       = Zend_Registry::get('config');
    $caching      = (boolean) $config->smarty->caching;
    $debugging    = (boolean) $config->smarty->debugging;
    $fCompile     = (boolean) $config->smarty->force_compile;
    $compileCheck = (boolean) $config->smarty->compile_check;

    Zend_Registry::set('smarty_config', array(
        'caching'        => $caching,
        'cache_lifetime' => $config->smarty->cache_lifetime,
        'template_dir'   => dirname(__FILE__).$config->smarty->template_dir,
        'compile_dir'    => dirname(__FILE__).$config->smarty->compile_dir,
        'config_dir'     => dirname(__FILE__).$config->smarty->config_dir,
        'cache_dir'      => dirname(__FILE__).$config->smarty->cache_dir,
        'debugging'      => $debugging,
        'force_compile'  => $fCompile,
        'compile_check'  => $compileCheck,
        'left_delimiter' => '{',
        'right_delimiter' => '}'
        ));
}

/**
 * Inits localization support
 *
 * @return void
 *
 */
function initLocale()
{
    include 'Zend/Locale.php';
    include 'Zend/Date.php';
    include 'Zend/Session/Namespace.php';
    include 'Zend/Translate.php';

    $config = Zend_Registry::get('config');
    date_default_timezone_set($config->timezone);


    Zend_Locale::setDefault($config->languages->default);
    //Zend_Locale::setCache(Zend_Registry::get('cache'));

    $locale      = new Zend_Locale($config->languages->default);
    $langSession = new Zend_Session_Namespace('Lang');

    if (isset($langSession->lang)) {
        $locale->setLocale($langSession->lang);
    }

    if (array_key_exists('lng', $_GET)) {
        $locale->setLocale($_GET['lng']);
        $langSession->lang = $_GET['lng'];
    }

    if ($locale->getLanguage() <> 'da' && $locale->getLanguage() <> 'en') {
        $locale->setLocale($config->languages->default);
    }



    $date = new Zend_Date(null, Zend_Date::ISO_8601, $locale->getLanguage());
    $date->setTimezone($config->timezone);
    Zend_Registry::set('date', $date);
    Zend_Date::setOptions(array(
        //'cache' => Zend_Registry::get("cache"),
        'format_type' => 'php'
    ));


    //Zend_Translate::setCache(Zend_Registry::get('cache'));
             
    /*$translate = new Zend_Translate('gettext',
	dirname(__FILE__).DIRECTORY_SEPARATOR.'..'
        .DIRECTORY_SEPARATOR.'languages'
        .DIRECTORY_SEPARATOR.'da'
        .DIRECTORY_SEPARATOR.'messages.mo', 'da');

    $translate->addTranslation(dirname(__FILE__).DIRECTORY_SEPARATOR.'..'
        .DIRECTORY_SEPARATOR.'languages'
        .DIRECTORY_SEPARATOR.'en'
        .DIRECTORY_SEPARATOR.'messages.mo', 'en');


            $translate->setLocale($locale->getLanguage()."_".$locale->getRegion());
*/
            Zend_Registry::set('locale', $locale);
            //Zend_Registry::set('tr', $translate);
}

/**
 * Inits Zend_Cache
 *
 * @return void
 *
 */
function initCache()
{
    include 'Zend/Cache.php';

    if (extension_loaded('memcache')) {
        $frontendOptions = array(
                'lifetime' => 7200, // cache lifetime of 2 hours
                'automatic_serialization' => true
        );
        $backendOptions  = array();
        $frontend        = 'Core';
        $backend         = 'Memcached';
    } elseif (extension_loaded('apc')) {
        $frontend = 'Core';
        $backend = 'Apc';
        $frontendOptions = array(
                'lifetime' => 7200, // cache lifetime of 2 hours
                'automatic_serialization' => true
        );
        $backendOptions  = array();
        //echo 'apc';
    } else {
        $frontendOptions = array(
            'lifetime' => 7200, // cache lifetime of 2 hours
            'automatic_serialization' => true
        );
        $backendOptions  = array(
            'cache_dir' => dirname(__FILE__).'/../tmp/cache' // Directory where to
        // put the cache files
        );
        $frontend        = 'Core';
        $backend         = 'File';
    }

    $cache = Zend_Cache::factory($frontend, $backend,
    $frontendOptions, $backendOptions);
    Zend_Registry::set('cache', $cache);
}

/**
 * Inits Zend_Logger
 *
 * @return void
 */

function initLogger(){
    include 'Zend/Log.php';
    include 'Zend/Log/Writer/Stream.php';
    
    $logger     = new Zend_Log();
    $fileWriter = new Zend_Log_Writer_Stream(dirname(__FILE__).'/../logs/out.log');
    $logger->addWriter($fileWriter);
    Zend_Registry::set('logger',$logger);
}

function initDoctrine(){

    require 'Doctrine.php';
    spl_autoload_register(array('Doctrine', 'autoload'));
    
    //Doctrine::compile();
    
    //require_once 'Doctrine.compiled.php';
    //include 'Doctrine/Manager.php';
    //include 'Doctrine/Cache/Apc.php';
    //include 'Doctrine/Cache/Memcache.php';

    $config = Zend_Registry::get('config');

    Zend_Registry::set('doctrine_config', array(
        'data_fixtures_path' => dirname(__FILE__).'/doctrine/data/fixtures',
        'models_path'        => dirname(__FILE__).'/Model',
        'migrations_path'    => dirname(__FILE__).'/Doctrine/migrations',
        'sql_path'           => dirname(__FILE__).'/Doctrine/data/sql',
        'yaml_schema_path'   => dirname(__FILE__).'/Doctrine/schema',
    ));

    //$manager = Doctrine_Manager::getInstance();
    $conn = Doctrine_Manager::connection($config->db->type.'://'
    .$config->db->username.':'
    .$config->db->password.'@'
    .$config->db->host.'/'
    .$config->db->name);
     
    $conn->setOption('username', $config->db->username);
    $conn->setOption('password', $config->db->password);

    $servers = array('host' => 'localhost',
                     'port' => 11211,
                     'persistent' => true);

    if (extension_loaded('memcache')) {
        $cacheDriver = new Doctrine_Cache_Memcache(array('servers' => $servers,
                                                    'compression' => true));
        //$cacheDriver = new Doctrine_Cache_Apc();
        $conn->setAttribute(Doctrine::ATTR_QUERY_CACHE, $cacheDriver);
        $conn->setAttribute(Doctrine::ATTR_RESULT_CACHE, $cacheDriver);
    }

}

function initTestEnv()
{
    if (!array_key_exists('HTTP_HOST', $_SERVER)) {
        $_SERVER['HTTP_HOST'] = 'testind.data2people.com';
    }
}

function initAuth()
{
    //include 'Zend/Auth.php';
    //include 'TS/Auth/Acl.php';
    //include 'TS/Auth/Storage.php';
    /**
     * Instantiate Zend_Auth
     */
    /*
    $auth = Zend_Auth::getInstance();
    $auth->setStorage(new TS_Auth_Storage());
    $acl = new TS_Auth_Acl();

    Zend_Registry::set('auth', $auth);
    Zend_Registry::set('acl', $acl);*/

}

function initSession()
{
    /**
     * Start session
     */

    Zend_Session::start();

    $defaultNamespace = new Zend_Session_Namespace();

    if (!isset($defaultNamespace->initialized)) {
        Zend_Session::regenerateId();
        $defaultNamespace->initialized = true;
    }

}

function initConfigXML()
{
    defined('STAGING')
            or define('STAGING', 'dev');
            
    $config = new Zend_Config_Xml(APP_PATH.DIRECTORY_SEPARATOR
                                 .'Config/settings.xml', STAGING);
    Zend_Registry::set('config', $config);
    
}